package org.jeecg.modules.basic.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.basic.attendance.entity.LwgyInoutAttendance;
import org.jeecg.modules.basic.attendance.service.ILwgyInoutAttendanceService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author sn
 * @date 2022-09-23 15:20
 *  //考勤异常界定。目前10点界定晚归，12点界定未归，后期改为灵活的  bf后期删除
 *
 */
@Slf4j
public class UnusualKqWgInfoJobbf implements Job {


    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;
    @Autowired
    private ILwgyInoutAttendanceService lwgyInoutAttendanceService;


    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" 时间:" + DateUtils.getTimestamp()));
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 构造昨天10点的时间
        LocalDateTime yesterdayTenAM = LocalDateTime.of(yesterday, LocalTime.of(22, 0));
        // 构造昨天23点59分的时间
        LocalDateTime yesterdayElevenFiftyNinePM = LocalDateTime.of(yesterday, LocalTime.of(23, 59));
        // 格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 构建 QueryWrapper
        QueryWrapper<LwgyInoutAttendance> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id"); // 指定要查询的字段
        queryWrapper.select("student_name"); // 指定要查询的字段
        queryWrapper.select("student_number"); // 指定要查询的字段
        queryWrapper.select("student_campus"); // 指定要查询的字段
        queryWrapper.select("student_college"); // 指定要查询的字段
        queryWrapper.select("student_major"); // 指定要查询的字段
        queryWrapper.select("student_class"); // 指定要查询的字段
        queryWrapper.select("student_year"); // 指定要查询的字段
        queryWrapper.select("position"); // 指定要查询的字段
        queryWrapper.select("sign_time"); // 指定要查询的字段
        queryWrapper.select("sign_result"); // 指定要查询的字段
        queryWrapper.likeRight("sign_time", yesterday);

        //今天凌晨1点执行（比如）查询昨天所有的打卡记录
        List<LwgyInoutAttendance> kqlist =lwgyInoutAttendanceService.list(queryWrapper);
        List<LwgyBaseStudent> userList = new ArrayList<>();
        System.out.println("======:"+kqlist.size());
        if(kqlist.size()>0) {
            // 判断是否晚归
            for (LwgyInoutAttendance record : kqlist) {

                LocalDateTime currentTime = LocalDateTime.parse( record.getSignTime().toString(), formatter);
                if (currentTime.isAfter(yesterdayTenAM)) {
                    System.out.println("晚归打卡： " + record.getSignTime());
                    record.setSignResult("1");
                } else {
                    record.setSignResult("0");
                }

            }
            lwgyInoutAttendanceService.updateBatchById(kqlist);

            //筛选出所有的学号，查询没打卡学生用
            String[] numbers = kqlist.stream().map(p -> p.getStudentNumber()).collect(Collectors.toList()).toArray(new String[0]);
            QueryWrapper<LwgyBaseStudent> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.notIn("user_id", numbers);


            // 执行查询
             userList = lwgyBaseStudentService.list(queryWrapper2);
        }else{
             userList = lwgyBaseStudentService.list();
        }

        // 输出未打卡的用户列表
        List<LwgyInoutAttendance> newlist  =  new ArrayList<>();
        for (LwgyBaseStudent user : userList) {
            LwgyInoutAttendance attendance = new LwgyInoutAttendance();
            attendance.setCreateBy("自动核查");
            attendance.setStudentName(user.getStudentName());
            attendance.setStudentNumber(user.getStudentNumber());
            attendance.setStudentCampus(user.getStudentCampus());
            attendance.setStudentCollege(user.getStudentCollege());
            attendance.setStudentMajor(user.getStudentMajor());
            attendance.setStudentClass(user.getStudentClass());
            attendance.setStudentYear(user.getStudentYear());
            attendance.setSignType("0");
            attendance.setPosition("无");
            attendance.setSignResult("2");
            attendance.setSignTime( new Date(Timestamp.valueOf(yesterdayElevenFiftyNinePM).getTime()));
            newlist.add(attendance);
        }
        System.out.println(new Date(Timestamp.valueOf(yesterdayElevenFiftyNinePM).getTime()));
        lwgyInoutAttendanceService.saveBatch(newlist);


    }
}
